//
//  ZDCreateOrderController.m
//  特种车调度
//
//  Created by 陈宇 on 15/8/20.
//
//

#import "ZDCreateOrderController.h"
#import "ZDCarButton.h"
#import "REMenu.h"
#import "ZDTruck.h"
#import "OrderManager.h"
#import "BMAccountManager.h"
#import "BMLoginController.h"
#import "ZDBaseNavController.h"
//#import "ZDSelectPayController.h"
//#import "ZDController.h"
//#import "ZDOrderDetailController.h"
//#import "BMSpinnerView.h"
#import "TCPersonViewController.h"

@interface ZDCreateOrderController () <UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) NSArray *truckStyles;
@property (nonatomic, strong) StylePrice *currentPrice;
//@property (nonatomic, strong) OrderManager *manager;
//@property (nonatomic, strong) BMSpinnerView *spinnerView;

#pragma mark - 只有在小屏幕上需要计算滑动距离
@property (weak, nonatomic) IBOutlet UILabel *totalpriceLabel;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *outerView;
@property (weak, nonatomic) IBOutlet UIView *innerView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;
@property (weak, nonatomic) IBOutlet UITextField *fangTextfield;
@property (weak, nonatomic) IBOutlet UITextField *liangTextfield;
@property (weak, nonatomic) IBOutlet UITextField *remarkTextfield;

#pragma mark - 上方三个车型
@property (weak, nonatomic) IBOutlet ZDCarButton *tongButton;
@property (weak, nonatomic) IBOutlet ZDCarButton *chezaiButton;
@property (weak, nonatomic) IBOutlet ZDCarButton *qiButton;
//
@property (nonatomic, weak) ZDCarButton *currentButton;
@property (nonatomic, strong) REMenu *featureMenu;
@property (weak, nonatomic) IBOutlet UILabel *featureLabel;
@property (weak, nonatomic) IBOutlet UILabel *featureValueLabel;
@property (weak, nonatomic) IBOutlet UITextField *singlePriceTextfield;
@property (weak, nonatomic) IBOutlet UILabel *singlePriceLabel;
- (IBAction)changeSingleActoin:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UIButton *sendButton;

#pragma mark - 时间选择
@property (nonatomic, weak) UITextField *dateTf;
@property (nonatomic, weak) UIPickerView *pickerView;
@property (nonatomic, strong) NSMutableArray *com1Date;
@property (nonatomic, strong) NSMutableArray *com1;
@property (nonatomic, strong) NSMutableArray *com2;
@property (nonatomic, strong) NSMutableArray *com3;
@property (nonatomic, copy) NSString *selectDate;

@property (weak, nonatomic) IBOutlet UILabel *dateLabel;


- (IBAction)exitAction:(id)sender;
- (IBAction)changeCar:(UITapGestureRecognizer *)recognizer;
- (IBAction)showFeature:(UITapGestureRecognizer *)recognizer;
- (IBAction)dateAction:(id)sender;
- (IBAction)toolbarCancle:(id)sender;
- (IBAction)toolbarOK:(id)sender;

@end

@implementation ZDCreateOrderController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.manager = [[OrderManager alloc] init];
    
    [self configuration];
    
    [self initDatas];
    
    [self loadCarInfo];
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)configuration {
    
    self.tongButton.title = @"砼车";
    self.chezaiButton.title = @"车载泵";
    self.qiButton.title = @"汽泵";
    
    self.tongButton.image = [UIImage imageNamed:@"tong"];
    self.chezaiButton.image = [UIImage imageNamed:@"chezai"];
    self.qiButton.image = [UIImage imageNamed:@"qi"];
    self.tongButton.selectImage = [UIImage imageNamed:@"tong_select"];
    self.chezaiButton.selectImage = [UIImage imageNamed:@"chezai_select"];
    self.qiButton.selectImage = [UIImage imageNamed:@"qi_select"];
    
    self.fangTextfield.delegate = self;
    
    UITextField *dateTF = [UITextField new];
    UIPickerView *inputView = [[UIPickerView alloc] init];
    inputView.delegate = self;
    inputView.dataSource = self;
    dateTF.inputView = inputView;
    dateTF.inputAccessoryView = [[[NSBundle mainBundle] loadNibNamed:@"InputToolbar" owner:self options:nil] firstObject];
    [self.view addSubview:dateTF];
    self.dateTf = dateTF;
    self.pickerView = inputView;
    [self.sendButton setTitle:@"下单" forState:UIControlStateNormal];
    
    self.liangTextfield.text = @"1";
}

- (void)initDatas
{
    _com1Date = [NSMutableArray array];
    _com1 = [NSMutableArray array];
    _com2 = [NSMutableArray array];
    _com3 = [NSMutableArray array];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"MM月dd日";
    NSTimeInterval oneDay = 24 * 60 * 60 * 1;  //1天的长度
    
    for (int i = 0; i <= 20; i++) {
        NSDate *date = [NSDate dateWithTimeIntervalSinceNow:oneDay * i];
        [_com1Date addObject:date];
        [_com1 addObject:[formatter stringFromDate:date]];
    }
    
    for (int i = 0; i < 24; i++) {
        [_com2 addObject:[NSString stringWithFormat:@"%02d点", i]];
    }
    
    for (int i = 0; i <= 12; i++) {
        [_com3 addObject:[NSString stringWithFormat:@"%02d分", i * 5]];
    }
}

- (REMenu *)featureMenu
{
    if (!_featureMenu) {
        _featureMenu = [[REMenu alloc] init];
    }
    return _featureMenu;
}

- (void)loadCarInfo
{
    weakSelf(self);
    [self showHudWithhint:kDefaultMessage];
    BMRequest *request = [BMRequest requestWithPath:@"/getTruckStyle1PriceList.htm" contentKey:@"TruckStyleList"];
    [ZDTruck postWithRequest:request finish:^(BMResponse *response, NSError *error) {
        [weakSelf hideHud];
        if (response.status == 1) {
            weakSelf.truckStyles = response.result;
//            switch (weakSelf.defaultIndex) {
//                case 0:
////                    weakSelf.currentButton = weakSelf.tongButton;
//                    break;
//                case 1:
////                    weakSelf.currentButton = weakSelf.chezaiButton;
//                    break;
//                case 2:
////                    weakSelf.currentButton = weakSelf.qiButton;
//                    break;
//            }
        } else {
            [self showHint:@"获取车辆信息失败!"];
        }
    }];
}

- (void)viewDidAppear:(BOOL)animated
{
    CGFloat offert = CGRectGetMaxY([_innerView.subviews.lastObject frame]) - _outerView.height;
    _bottomConstraint.constant -= offert;
}

- (IBAction)exitAction:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)sendAction:(UIButton *)sender {
    NSInteger fang = [self.fangTextfield.text integerValue];
    if (!fang) {
        [self showHint:@"请填写正确方放量"];
        return;
    }
    NSInteger liang = [self.liangTextfield.text integerValue];
    if (!liang) {
        [self showHint:@"请填写期望的车辆数"];
        return;
    }
    if (!self.selectDate) {
        [self showHint:@"请选择期望的用车时间"];
        return;
    }
//    if (!self.currentPrice) {
//        if (_currentButton == _tongButton) {
//            [self showHint:@"请选择运输距离"];
//        } else if (_currentButton == _chezaiButton) {
//            [self showHint:@"请选择车型"];
//        } else if (_currentButton == _qiButton) {
//            [self showHint:@"请选择臂长"];
//        }
//        return;
//    }
    
//    if (_currentButton == _chezaiButton || _currentButton == _qiButton) {
//        if (liang > 2) {
//            [self showHint:@"单次下单不能超过2辆"];
//            return;
//        }
//    }
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH-mm";
    NSDate *selectDate = [dateFormatter dateFromString:self.selectDate];
    NSDate *currentDate = [NSDate new];
    BOOL early = [selectDate isEarlierThanDate:currentDate];
    if (early) {
        [self showHint:@"用车时间不能早于当前时间"];
        return;
    }
    
    if (![BMAccountManager sharedInstance].isLogin) {
        UINavigationController *navVC = [self.storyboard instantiateViewControllerWithIdentifier:@"loginVC"];
        BMLoginController *loginVC = (id)navVC.topViewController;
        loginVC.type = 1;
        [self presentViewController:navVC animated:YES completion:nil];
        return;
    }
    
    void (^commitOP)() = ^ {
        ZDOrder *order = [ZDOrder new];
        order.style = self.currentPrice;
        order.volume = [self.fangTextfield.text doubleValue];
        order.count = liang;
        order.name = self.selectDate;   //由于对appointmentTime进行了特殊处理，故使用name字段
        order.changeUnitPrice = self.singlePriceTextfield.text;
        order.remarks = self.remarkTextfield.text;
        order.sumPrice = [self calculateTotalPrice];
        order.style.name = self.currentButton.title;
//
//        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:[NSString stringWithFormat:@"该订单将从账户中冻结金额¥%.f元，确定创建？", order.sumPrice] preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//        [alertVC addAction:cancleAction];
//        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//            [self showHudWithhint:kDefaultMessage];
//            [self.manager createOrder:order complete:^(BMResponse *response, NSError *error) {
//                [self hideHud];
//                if (response.status == kResultOK) {
//                    NSInteger orderID = [[response.rawResult objectForKey:@"orderId"] integerValue];
//                    ZDOrder *order = [ZDOrder new];
//                    order.ID = orderID;
//                    UINavigationController *navVC = (id)self.presentingViewController;
//                    [self dismissViewControllerAnimated:YES completion:^{
//                        ZDOrderDetailController *detailVC = [self.storyboard instantiateViewControllerWithIdentifier:@"orderDetailVC"];
//                        detailVC.order = order;
//                        [navVC pushViewController:detailVC animated:YES];
//                    }];
//                    [self showHint:@"下单成功"];
//                } else if (response.status == 8) {  //余额不足
//                    ZDSelectPayController *payVC = [self.storyboard instantiateViewControllerWithIdentifier:@"selectPayVC"];
//                    payVC.type = 1;
//                    ZDBaseNavController *navVC = [[ZDBaseNavController alloc] initWithRootViewController:payVC];
//                    [self showViewController:navVC sender:nil];
//                } else if (response.status == 9) {  //未选择站点
//                    ZDController *destVC = [self.storyboard instantiateViewControllerWithIdentifier:@"zdVC"];
//                    destVC.type = 1;
//                    ZDBaseNavController *navVC = [[ZDBaseNavController alloc] initWithRootViewController:destVC];
//                    [self showViewController:navVC sender:nil];
//                } else {
//                    [self showHint:response.msg];
//                }
//            }];
//        }];
//        [alertVC addAction:okAction];
        //    [cancleAction setValue:kGlobalColor forKeyPath:@"titleTextColor"];
        //    [okAction setValue:kGlobalColor forKeyPath:@"titleTextColor"];
//        [self presentViewController:alertVC animated:YES completion:nil];
//    };
    
//    double sfang = (double)fang / liang;
//    NSString *msg = @"";
//    
//    if (_currentButton == _tongButton) {
//        if (sfang < 20) {
//            [self showHint:@"砼车下单方量不能低于20方"];
//            return;
//        } else if (sfang < 40) {
//            msg = @"建议最少为每台车分配40方量,是否继续?";
//        }
//    } else {
//        if (sfang < 50) {
////            msg = @"建议最少为每台车分配50方量,是否继续?";
//            [self showHint:@"建议最少为每台车分配50方量"];
//            return;
//        }
//    }
//    
//    if (![BMUtils isEmptyString:msg]) {
//        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:msg preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//        [alertVC addAction:cancleAction];
//        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//            
//            commitOP();
//            
//        }];
//        [alertVC addAction:okAction];
//        //    [cancleAction setValue:kGlobalColor forKeyPath:@"titleTextColor"];
//        //    [okAction setValue:kGlobalColor forKeyPath:@"titleTextColor"];
//        [self presentViewController:alertVC animated:YES completion:nil];
//        //        [self showHint:@"每辆车不能少于40方,请增加方量"];
//        //        return;
//    } else {
//        commitOP();
    };
}

//- (IBAction)changeCar:(UITapGestureRecognizer *)recognizer
//{
//    UIView *targetView = recognizer.view;
//    if (targetView == _currentButton) return;
//    
//    self.currentButton = (id)targetView;
//}

//- (void)setCurrentButton:(ZDCarButton *)currentButton
//{
//    _currentButton.selected = NO;
//    _currentButton = (id)currentButton;
//    _currentButton.selected = YES;
//    
//    StylePrice *price;
//    if (_currentButton == _tongButton) {
//        price = [self.truckStyles[0] stylePrice].firstObject;
//    } else if (_currentButton == _chezaiButton) {
//        price = [self.truckStyles[1] stylePrice].firstObject;
//    } else if (_currentButton == _qiButton) {
//        price = [self.truckStyles[2] stylePrice].firstObject;
//    }
//    self.featureLabel.text = price.conditionName;
//    self.currentPrice = nil;
//}

- (void)setCurrentPrice:(StylePrice *)currentPrice
{
    _currentPrice = currentPrice;
    self.featureValueLabel.text = _currentPrice.condition;
    self.singlePriceLabel.text = _currentPrice.price;
    [self calculateTotalPrice];
}

- (IBAction)showFeature:(UITapGestureRecognizer *)recognizer
{
    [self.view endEditing:YES];
    //    NSMutableArray *items = [NSMutableArray array];
    //    weakSelf(self);
    //    NSArray *prices = [self.truckStyles[_currentButton.tag] stylePrice];
    //    for (int i = 0; i < prices.count; i++) {
    //        REMenuItem *item = [[REMenuItem alloc] initWithTitle:nil image:nil highlightedImage:nil action:^(REMenuItem *item) {
    //            weakSelf.currentPrice = item.price;
    //        }];
    //        item.price = prices[i];
    //        [items addObject:item];
    //    }
    //    self.featureMenu.items = items;
    //    [self.featureMenu showInView:self.view yOffset:20.f];
//    [self.spinnerView showBelowWith:recognizer.view];
}

- (IBAction)dateAction:(id)sender {
    [self.dateTf becomeFirstResponder];
}

- (IBAction)toolbarCancle:(id)sender {
    [self.dateTf resignFirstResponder];
}

- (IBAction)toolbarOK:(id)sender {
    NSDate *date = _com1Date[[self.pickerView selectedRowInComponent:0]];
    NSString *com2Str = _com2[[self.pickerView selectedRowInComponent:1]];
    NSString *com3Str = _com3[[self.pickerView selectedRowInComponent:2]];
    [self.dateTf resignFirstResponder];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"MM-dd";
    self.dateLabel.text = [NSString stringWithFormat:@"%@ %@:%@", [formatter stringFromDate:date], [com2Str substringToIndex:com2Str.length - 1], [com3Str substringToIndex:com3Str.length - 1]];
    formatter.dateFormat = @"yyyy-MM-dd";
    NSString *selectDate = [formatter stringFromDate:date];
    selectDate = [selectDate stringByAppendingFormat:@" %@:%@", com2Str, com3Str];
    selectDate = [selectDate stringByReplacingOccurrencesOfString:@"点" withString:@""];
    self.selectDate = [selectDate stringByReplacingOccurrencesOfString:@"分" withString:@""];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
        return _com1.count;
    } else if (component == 1) {
        return _com2.count;
    } else if (component == 2) {
        return _com3.count;
    }
    return 0;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0) {
        return _com1[row];
    } else if (component == 1) {
        return _com2[row];
    } else if (component == 2) {
        return _com3[row];
    }
    return nil;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        pickerLabel.textColor = [UIColor darkGrayColor];
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setFont:[UIFont systemFontOfSize:14.f]];
    }
    // Fill the label text here
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

- (IBAction)changeSingleActoin:(UIButton *)sender {
    NSInteger offset = [self.singlePriceTextfield.text integerValue];
    if (sender.tag) {
        offset++;
    } else {
        if (offset > 0) {
            offset--;
        }
    }
    self.singlePriceTextfield.text = [NSString stringWithFormat:@"%ld", offset];
    [self calculateTotalPrice];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self calculateTotalPrice];
}

- (double)calculateTotalPrice
{
    double fang = self.fangTextfield.text.doubleValue;
    double singlePrice = [self.currentPrice.price doubleValue];
    if (singlePrice) {
        singlePrice += self.singlePriceTextfield.text.integerValue;
    }
    self.totalpriceLabel.text = [NSString stringWithFormat:@"%.2f", fang * singlePrice];
    return fang * singlePrice;
}

//- (BMSpinnerView *)spinnerView
//{
//    if (!_spinnerView) {
//        _spinnerView = [[BMSpinnerView alloc] init];
//        _spinnerView.dataSource =self;
//        _spinnerView.delegate =self;
//    }
//    return _spinnerView;
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 10; //return [self.truckStyles[_currentButton.tag] stylePrice].count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.font = [UIFont systemFontOfSize:13.f];
        cell.textLabel.textColor = [UIColor darkGrayColor];
    }
//    StylePrice *price = [self.truckStyles[_currentButton.tag] stylePrice][indexPath.row];
//    cell.textLabel.text = price.condition;
    cell.backgroundColor = [UIColor redColor];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    TCPersonViewController *TC  = [[TCPersonViewController alloc]init];
//    [self presentViewController:TC animated:YES completion:nil];
//    self.currentPrice = [self.truckStyles[_currentButton.tag] stylePrice][indexPath.row];
//    [self.spinnerView hideWithAnimate:YES];
}

@end
